package com.jlkf.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.dao.TblIntegralSetMapper;
import com.jlkf.dao.TblOrderMapper;
import com.jlkf.dao.TblRelationMapper;
import com.jlkf.dao.TblRoleMapper;
import com.jlkf.dao.TblSysUserMapper;
import com.jlkf.pojo.TblIntegralSet;
import com.jlkf.pojo.TblOrder;
import com.jlkf.pojo.TblProfessionInfo;
import com.jlkf.pojo.TblRelation;
import com.jlkf.pojo.TblRole;
import com.jlkf.pojo.TblSysUser;
import com.jlkf.pojo.TblUser;
import com.jlkf.service.SysUserService;
import com.jlkf.view.ExcelRole;
import com.jlkf.view.ExcelSysUser;
import com.jlkf.view.ExcelUserInfo;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.ExportExcel;
import com.platform.server.util.MD5Util;
import com.platform.server.util.StringTools;

@Controller
@RequestMapping("sysUser")
public class SysUserController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private TblRoleMapper tblRoleMapper;
	@Autowired
	private TblOrderMapper tblOrderMapper;
	@Autowired
	private TblIntegralSetMapper tblIntegralSetMapper;
	@Autowired
	private TblSysUserMapper sysUserMapper;
	
	@RequestMapping("loginUser")
	@ResponseBody
	public ReturnData loginUser(@RequestBody String json,HttpSession session){
		try{
			Map<String, Object> map = StringTools.jsonToMap(json);
		    String phone = map.get("phone").toString();
		    String pwd = map.get("password").toString();
		    
		    if(StringTools.isEmpty(phone)){
		        return new ReturnData(500,"用户名不能为空");
		    }
		    
		    if(StringTools.isEmpty(pwd)){
		    	return new ReturnData(500,"密码不能为空");
		    }
		    Map<String, Object> map2 = new HashMap<String,Object>();
		    map2.put("gAccount", phone);
		    map2.put("gPassword", MD5Util.getMD5byBase64(pwd));
		    
		    TblSysUser sysUser = sysUserService.loginUser(map2);
		    if(sysUser!=null){
		    	if(sysUser.getgStatus()==2){
		    		return new ReturnData(500,"你的账号已被禁用，请联系管理员");
		    	}else{
		    		session.setMaxInactiveInterval(-1);
		    		session.setAttribute("sysUser", sysUser);
		    		if(sysUser.getgRole()!=null && sysUser.getgRole()!=0){
						TblRole r = sysUserService.getRoleDetail(sysUser.getgRole());
						session.setAttribute("r", r);
					}
		    		return new ReturnData(200,"登录成功");
		    	}
		    }else{
		    	return new ReturnData(500,"账号或密码错误");
		    }
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	

	/**
	 * 退出
	 * @param request
	 * @param response
	 */
	@RequestMapping("loginout")
	@ResponseBody
	public void loginout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.removeAttribute("sysUser");
		// mode.setViewName("login");
		try {
			response.getWriter().write("<script>window.top.location.href=\"../login.jsp\";</script>");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 账户列表
	 * @param startTime
	 * @param endTime
	 * @param name
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("getUserInfo")
	@ResponseBody
	public ReturnData getUserInfo(String startTime,String endTime,String name,Integer status,Integer pageNumber,Integer pageSize,HttpSession session){
		try{
			TblSysUser user = (TblSysUser) session.getAttribute("sysUser");
			Map<String, Object> map = new HashMap<String,Object>();
			if(!StringTools.isEmpty(startTime)){
				map.put("startTime", startTime);
			}
			if(!StringTools.isEmpty(endTime)){
				map.put("endTime", endTime);
			}
			if(!StringTools.isEmpty(name)){
				map.put("name", name);
			}
			if(status!=null){
				map.put("status", status);
			}
			
			PageHelper.startPage(pageNumber,pageSize);
			List<TblSysUser> list = sysUserService.getSysUserList(map);
			//在列表中清除当前登录账号信息
			if (list != null && list.size() > 0) {
				Iterator<TblSysUser> it = list.iterator();
				while (it.hasNext()) {
					TblSysUser su = it.next();
					if (user.getgAccount().equals(su.getgAccount())) {
						it.remove();
					}
				}
			}
			PageInfo<TblSysUser> pageInfo = new PageInfo<>(list);
			return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"账户列表");
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 新增或修改账户信息
	 */
	@RequestMapping("insertOrUpdate")
	@ResponseBody
	public ReturnData insertOrUpdate(@RequestBody String json){
		try{
			TblSysUser sysUser = StringTools.json2Obj(json, TblSysUser.class);
			int num = 0;
			if(sysUser.getgId()!=null){
				String password = MD5Util.getMD5byBase64(sysUser.getgPassword());
				sysUser.setgPassword(password);
				sysUser.setgOldPassword(password);
				num = sysUserService.updateSysUser(sysUser);
			}else{
				int count = sysUserMapper.selectByAccount(sysUser.getgAccount());
			    if(count>0){
			    	return new ReturnData(500,"该账号已被添加，请重新输入账号");
			    }
				if(sysUser.getgRole()==null){
					TblRole role = tblRoleMapper.selectByRoleName();
					if(role==null){
						return new ReturnData(500,"请先添加‘代理人员’该角色");
					}
					sysUser.setgRole(role.getgId());
				}
				String password = MD5Util.getMD5byBase64(sysUser.getgPassword());
				sysUser.setgPassword(password);
				sysUser.setgOldPassword(password);
				sysUser.setgCreateDate(new Date());
				num = sysUserService.insertSysUser(sysUser);
			}
			if(num>0){
				return new ReturnData(sysUser.getgId(),200,"操作成功");
			}else{
				return new ReturnData(500,"操作失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
     * 账户详情
     */
    @RequestMapping("userDetail")
	@ResponseBody
	public ModelAndView userDetail(Integer gId,Integer type){
		TblSysUser user = sysUserService.getSysUserDetail(gId);
		ModelAndView andView = new ModelAndView();
    	andView.addObject("user",user);
    	if(type==1){
    		andView.setViewName("jsp/sysUserManager/addOrUpdateUser");
    	}else{
    		andView.setViewName("jsp/sysUserManager/addOrUpdateAgent");
    	}
		return andView;
	}
    
    /**
	 * 批量删除
	 * @param gId
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public ReturnData delete(String gId){
		List<String> list = Arrays.asList(gId.split(","));
		int rel = sysUserService.delete(list);
		if(rel>0){
			return new ReturnData(200,"删除成功");
		}else{
			return new ReturnData(500,"删除失败");
		}
	}
	
	/**
	 * 重置密码
	 * @param gId
	 * @return
	 */
	@RequestMapping("resetPwd")
	@ResponseBody
	public ReturnData resetPwd(Integer gId){
		TblSysUser user = sysUserService.getSysUserDetail(gId);
		if(user!=null){
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("gId", gId);
			map.put("gPassword", user.getgOldPassword());
			int num = sysUserService.updatePwd(map);
			if(num>0){
				return new ReturnData(200,"重置成功");
			}else{
				return new ReturnData(500,"重置失败");
			}
		}else{
			return new ReturnData(500,"系统错误");
		}
	}
	
	// 导出报表
	@RequestMapping("exportExcel")
	public void exportExcel(HttpServletResponse response,String startTime,String endTime,String name,Integer status){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> map = new HashMap<String,Object>();
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		if(!StringTools.isEmpty(name)){
			map.put("name", name);
		}
		if(status!=null){
			map.put("status", status);
		}
		List<Object> list2 = new ArrayList<Object>();
		List<TblSysUser> list = sysUserService.getSysUserList(map);
		for(TblSysUser user:list){
			ExcelSysUser userInfo = new ExcelSysUser();
			userInfo.setAccount(user.getgAccount());
			userInfo.setCreateTime(DateUtil.format3(user.getgCreateDate()));
			userInfo.setName(user.getgName());
			userInfo.setRoleName(user.getRoleName());
			if(user.getgStatus()==1){
				userInfo.setStatus("启用");
			}else{
				userInfo.setStatus("禁用");
			}
			list2.add(userInfo);
		}
		String[] titles = { "账号", "姓名", "角色", "状态", "创建日期"};
		ExportExcel.exportExcel("账户信息表.xls", titles, list2, response);
	}
	
	
	/**
	 * 角色列表
	 * @param startTime
	 * @param endTime
	 * @param name
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("getRoleList")
	@ResponseBody
	public ReturnData getRoleList(String startTime,String endTime,String name,Integer pageNumber,Integer pageSize,HttpSession session){
		try{
			Map<String, Object> map = new HashMap<String,Object>();
			if(!StringTools.isEmpty(startTime)){
				map.put("startTime", startTime);
			}
			if(!StringTools.isEmpty(endTime)){
				map.put("endTime", endTime);
			}
			if(!StringTools.isEmpty(name)){
				map.put("name", name);
			}
			PageHelper.startPage(pageNumber,pageSize);
			List<TblRole> list = sysUserService.selectRoleList(map);
			PageInfo<TblRole> pageInfo = new PageInfo<>(list);
			return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"角色列表");
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 新增或修改角色权限
	 */
	@RequestMapping("insertOrUpdateRole")
	@ResponseBody
	public ReturnData insertOrUpdateRole(@RequestBody String json){
		try{
			TblRole role = StringTools.json2Obj(json, TblRole.class);
			int num = 0;
			if(role.getgId()!=null){
				num = sysUserService.updateRole(role);
			}else{
				role.setgCreateTime(new Date());
				num = sysUserService.insertRole(role);
			}
			if(num>0){
				return new ReturnData(200,"操作成功");
			}else{
				return new ReturnData(500,"操作失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
     * 角色详情
     */
    @RequestMapping("roleDetail")
	@ResponseBody
	public ModelAndView roleDetails(Integer gId){
		TblRole role = sysUserService.getRoleDetail(gId);
		ModelAndView andView = new ModelAndView();
    	andView.addObject("role",role);
    	andView.setViewName("jsp/sysUserManager/addOrUpdateUser");
		return andView;
	}
    
    /**
	 * 批量删除
	 * @param gId
	 * @return
	 */
	@RequestMapping("deleteRole")
	@ResponseBody
	public ReturnData deleteRole(Integer gId){
		Integer count = sysUserService.isBandRole(gId);
		if(count>0){
			return new ReturnData(500,"该角色已被账户绑定，暂不能删除");
		}else{
			int rel = sysUserService.deleteRole(gId);
			if(rel>0){
				return new ReturnData(200,"删除成功");
			}else{
				return new ReturnData(500,"删除失败");
			}
		}	
	}
	
	// 导出报表
	@RequestMapping("exportExcelRole")
	public void exportExcelRole(HttpServletResponse response,String startTime,String endTime,String name){
		Map<String, Object> map = new HashMap<String,Object>();
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		if(!StringTools.isEmpty(name)){
			map.put("name", name);
		}
		List<Object> list2 = new ArrayList<Object>();
		List<TblRole> list = sysUserService.selectRoleList(map);
		for(TblRole role:list){
			ExcelRole excelRole = new ExcelRole();
			excelRole.setAuthority(role.getgAuthority());
			excelRole.setCreateTime(DateUtil.format3(role.getgCreateTime()));
			excelRole.setRoleName(role.getgRoleName());
			list2.add(excelRole);
		}
		String[] titles = { "角色名称", "角色权限", "添加时间"};
		ExportExcel.exportExcel("角色信息表.xls", titles, list2, response);
	}
	
	/**
	 * 代理商列表
	 * @param startTime
	 * @param endTime
	 * @param name
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("getAgentInfo")
	@ResponseBody
	public ReturnData getAgentInfo(Integer pageNumber,Integer pageSize,HttpSession session){
		try{
			TblSysUser user = (TblSysUser) session.getAttribute("sysUser");
			TblRole role = (TblRole) session.getAttribute("r");
			PageHelper.startPage(pageNumber,pageSize);
			List<TblSysUser> list = new ArrayList<TblSysUser>();
			if(role.getgRoleName().contains("代理")){
				list.add(user);
			}else{
				list = sysUserService.getAgentList();
			}
			for(TblSysUser sysUser:list){ //统计出下级的消费总额
				List<TblRelation> list2 = sysUserService.selectRelationList(sysUser.getgId());
			    List<Integer> uIds = new ArrayList<Integer>();
			    Double money = 0.0; //消费总额
			    Double courseAgentMoney = 0.0; //购买代理课程
			    Double integralMoney = 0.0; //购买积分
			    Double courseAgentByIntegral = 0.0; //积分购买代理课程
			    for(TblRelation relation:list2){
			    	uIds.add(relation.getgJunior());
			    	
			    	Map<String, Object> map = new HashMap<>();
					map.put("userId", (long)relation.getgJunior());
					map.put("optime", relation.getgCreateTime());
				    courseAgentMoney += tblOrderMapper.selectCourseMoneyByUser(map); //购买代理课程
				    integralMoney += tblOrderMapper.selectIntegralMoneyByUser(map); //购买积分
				    courseAgentByIntegral += tblOrderMapper.selectCourseIntegralByUser(map); //积分购买代理课程

			    }
			    if(uIds.size()>0 && uIds!=null){
			    	money = tblOrderMapper.getTotalMoney(uIds);
			    }
			    sysUser.setTotalMoney(money); //消费总额
			    if(courseAgentByIntegral!=0.0){
			    	TblIntegralSet integralSet = tblIntegralSetMapper.selectByType(2); //积分换成余额
			    	int num = (int) Math.floor(courseAgentByIntegral/integralSet.getIntegral()); 
			        Double amount = integralSet.getMoney()*num;
			        courseAgentMoney = courseAgentMoney+amount;
			    }
			    sysUser.setCourseAgentMoney(courseAgentMoney); //购买代理课程消费总额
			    sysUser.setIntegralMoney(integralMoney); //购买积分消费总额
			    sysUser.setTotalAgentMoney(courseAgentMoney+integralMoney); //代理消费总额（积分+课程）
			    sysUser.setShareMoney((courseAgentMoney+integralMoney)*sysUser.getgProportion()/100); //分润总额
			}
			PageInfo<TblSysUser> pageInfo = new PageInfo<>(list);
			return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"代理商列表");
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 启用或禁用
	 * @param gId
	 * @return
	 */
	@RequestMapping("updateStatus")
	@ResponseBody
	public ReturnData updateStatus(Integer gId,Integer status){
		TblSysUser user = sysUserService.getSysUserDetail(gId);
		if(user!=null){
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("gId", gId);
			map.put("status", status);
			int num = sysUserService.updateStatus(map);
			if(num>0){
				return new ReturnData(200,"操作成功");
			}else{
				return new ReturnData(500,"操作失败");
			}
		}else{
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 下级列表
	 * @param startTime
	 * @param endTime
	 * @param name
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("getJuniorInfo")
	@ResponseBody
	public ReturnData getJuniorInfo(Integer gId,Integer pageNumber,Integer pageSize){
		try{
			TblSysUser sysUser = sysUserService.getSysUserDetail(gId);
			PageHelper.startPage(pageNumber, pageSize);
			List<TblRelation> list = sysUserService.selectRelationList(gId);
			for(TblRelation relation:list){
				Map<String, Object> map = new HashMap<>();
				map.put("userId", (long)relation.getgJunior());
				map.put("optime", relation.getgCreateTime());
				Double money = tblOrderMapper.getMoneyByUId((long)relation.getgJunior()); //消费总额
			    Double courseAgentMoney = tblOrderMapper.selectCourseMoneyByUser(map); //购买代理课程
			    Double integralMoney = tblOrderMapper.selectIntegralMoneyByUser(map); //购买积分
			    Double courseAgentByIntegral = tblOrderMapper.selectCourseIntegralByUser(map); //积分购买代理课程

			    if(courseAgentByIntegral!=0.0){
			    	TblIntegralSet integralSet = tblIntegralSetMapper.selectByType(2); //积分换成余额
			    	int num = (int) Math.floor(courseAgentByIntegral/integralSet.getIntegral()); 
			        Double amount = integralSet.getMoney()*num;
			        courseAgentMoney = courseAgentMoney+amount;
			    }
			    relation.setMoney(money);
			    relation.setCourseAgentMoney(courseAgentMoney); //购买代理课程消费总额
			    relation.setIntegralMoney(integralMoney); //购买积分消费总额
			    relation.setTotalAgentMoney(courseAgentMoney+integralMoney); //代理消费总额（积分+课程）
			    relation.setShareMoney((courseAgentMoney+integralMoney)*sysUser.getgProportion()/100); //分润总额
			}
			PageInfo<TblRelation> pageInfo = new PageInfo<>(list);
			return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"下级列表");
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 修改密码
	 * @param gId
	 * @return
	 */
	@RequestMapping("updatePwd")
	@ResponseBody
	public ReturnData updatePwd(@RequestBody String json,HttpSession session){
		try{
			Map<String, Object> map = StringTools.jsonToMap(json);
			String oldPwd = map.get("oldPwd").toString();
			String newPwd = map.get("newPwd").toString();
			String againNewPwd = map.get("againNewPwd").toString();
			
			TblSysUser sysUser = (TblSysUser) session.getAttribute("sysUser");
			if(sysUser!=null){
				if(!sysUser.getgPassword().equals(MD5Util.getMD5(oldPwd))){
					return new ReturnData(500,"原密码输入错误");
				}
				if(!newPwd.equals(againNewPwd)){
					return new ReturnData(500,"两次密码输入不一致");
				}
				Map<String, Object> map1 = new HashMap<String,Object>();
				map1.put("gId",sysUser.getgId());
				map1.put("gPassword", MD5Util.getMD5(newPwd));
				int num = sysUserService.updatePwd(map1);
				if(num>0){
					return new ReturnData(200,"修改成功");
				}else{
					return new ReturnData(500,"修改失败");
				}
			}else{
				return new ReturnData(500,"传入参数有误");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
}
